package nettyRPC.registry;

import nettyRPC.client.ConnectManger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @program: NettyRpc-master
 * @description
 * @author: tkk fendoukaoziji
 * @create: 2019-08-12 18:20
 **/
public class ServiceDiscovry {
    private static final Logger logger=LoggerFactory.getLogger(ServiceDiscovry.class);
    private CountDownLatch latch=new CountDownLatch(1);
    private volatile List<String> dataList=new ArrayList<>();
    private String registryAddress;
    private ZooKeeper zooKeeper;

    /**
     * 发现服务
     * @param registryAddress
     */
    public ServiceDiscovry(String registryAddress){
        this.registryAddress=registryAddress;
        zooKeeper=connectServer();
        if(zooKeeper!=null){
            watchNode(zooKeeper);
        }
    }

    public String discover(){
        String data=null;
        int size=dataList.size();
        if(size>0){
            if(size==1){
                data=dataList.get(0);
                logger.debug("using only data:{}",data);

            }else {
                data=dataList.get(ThreadLocalRandom.current().nextInt(size));
                logger.debug("using random data:{}",data);
            }
        }
        return data;
    }


    /**
     * 建立客户端连接
     * @return
     */
    private ZooKeeper connectServer(){
        ZooKeeper zk=null;
        try {
            zk=new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    if(watchedEvent.getState()==Event.KeeperState.SyncConnected){
                        latch.countDown();
                    }
                }
            });
            latch.await();
        } catch (InterruptedException e) {
           logger.error(e.toString());
        } catch (IOException e) {
            logger.error(e.toString());
        }
        return  zk;
    }

    /**
     * 建立监听
     * @param zk
     */
    private void watchNode(final ZooKeeper zk){
        try {
            List<String> nodeList = zk.getChildren(Constant.ZK_REGISTRY_PATH, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {
                        watchNode(zk);
                    }
                }
            });
            List<String> dataList = new ArrayList<>();
            for (String node : nodeList) {
                byte[] bytes = zk.getData(Constant.ZK_REGISTRY_PATH + "/" + node, false, null);
                dataList.add(new String(bytes));
            }
            logger.debug("node data：{}",dataList);
            this.dataList=dataList;
            logger.debug("Service discovery triggered updating connected server node");
            updateConnectedServer();
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void updateConnectedServer(){
        ConnectManger.getInstance().updateConnectedServer(this.dataList);
    }


    public void stop(){
        if(zooKeeper!=null){
            try {
                zooKeeper.close();
            } catch (InterruptedException e) {
                logger.error("",e);
            }
        }
    }
}
































